/*
 *@本js功能：镜像管理
 *@本js作者：杨锡君
 *@编写时间：2018年06月21日
 */
$(function() {
    var Alert1 = new Alert();
    var confirm1 = new Confirm();
    var loading1 = new Loading();
    loading1.init();
    var $tableBox = $(".tableBox");
    var th = "<tr>" +
        "<th class=\"col-lg-1\">序号</th>" +
        "<th class=\"col-lg-6\">镜像</th>" +
        // "<th class=\"col-lg-3\">来源</th>" +
        "<th class=\"col-lg-1\">状态</th>" +
        "<th  class=\"col-lg-4\" style='text-align: center' class=\"col-lg-3\">操作</th>" +
        "</tr>";
    function tabelModel(opt,startRow) {
        var statusCode = opt.statusCode;
        if(statusCode == 1){
            statusCode = "使用";
        }else{
            statusCode = "未使用";
        }
        var str = "<tr data-num=\"0\">" +
            "<td class=\"col-lg-1\">"+ startRow +"</td>" +
            "<td class=\"col-lg-4\" title="+ opt.name +">"+ opt.name +"</td>" +
            // "<td class=\"col-lg-3\" title="+ opt.imageSource +">"+ opt.imageSource +"</td>" +
            "<td class=\"col-lg-1\" title="+ statusCode +">"+ statusCode +"</td>" +
            "<td class=\"col-lg-3\">"+
            "<a href=\"javascript:;\"  data-id='"+ opt.id +"'   class=\"look\">查看</a>";
        if(opt.shared == true){
            str+= "<a href=\"javascript:;\"  data-id='"+ opt.id +"'   class=\"cancel\">取消同步公有</a>";
        }else {
            str+= "<a href=\"javascript:;\"  data-id='"+ opt.id +"'   class=\"submit\">同步到公有&emsp;</a>";
        }
        str+= "<a href=\"javascript:;\"  data-id='"+ opt.id +"'   class=\"detailBtn\">删除</a>" +
            "</td>"+
            "</tr>";
        return str;
    }
    var virMachineSch = {
        status:false,
        init: function() {
            this.bindEvent();
        },
        bindEvent: function() {
            var self = this;
            var json = {
                "pageNum": 1,
                "pageSize": 10
            };
            self.tabelList(json);
            self.getSaveNum();
        },
        getSaveNum:function () {
            $.ajax({
                type: "get",
                url: "manage/config/query",
                async: true,
                success: function(msg) {
                    if(msg.code == 200){
                        var msgNew = msg.data;
                        $(".saveNum").html(msgNew.imageQuota);
                    }
                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        exchange:function(json){
            var self = this;
            var jsonS = json;
            $(".look").off("click").click(function () {
                var id = Number($(this).attr("data-id"));
                var json = {"imageId":id};
                loading1.show();
                $.ajax({
                    type: "get",
                    url: "image/desktop",
                    data:json,
                    async: true,
                    success: function (msg) {
                        loading1.hide();
                        if(msg.code == 200) {
                            $("#ifMain",parent.document).css({"position":"fixed","left":0,"top":0,"z-index":100});
                            $("body").append("<div id='divIf'><div class='title'><img src='pc/images/ico_shareClose.png' class='fr cancelBtn' alt=''><div class='fr saveImg'>保存镜像</div></div><iframe id='ifBox' src='"+msg.data.desktopUrl +"' frameborder='0'></iframe></div>")
                            $("#divIf").css({"height":$("body",parent.document).height()+"px","width":$("body",parent.document).width()+"px"});
                            $("#ifBox").css({"height": $("#divIf").height()-40+"px","width": $("#divIf").width()+"px"});
                            startWebSocket(msg.data.containerId);
                            $(".cancelBtn").off("click").click(function () {
                                ws.close();
                                $("#ifMain",parent.document).attr("style","");
                                $("#divIf").remove();
                                self.tabelList(jsonS);
                            });
                            $(".exportCancle").off("click").click(function () {
                                $("#imgName").val("");
                                $(".popup,.masking").hide();
                            });
                            $(".popup_img").off("click").click(function () {
                                $("#imgName").val("");
                                $(".popup,.masking").hide();
                            });
                            $(".saveImg").off("click").click(function () {
                                $(".popup,.masking").show();
                                $(".exportBtn").off("click").click(function () {

                                    var json = JSON.stringify({"imageName":$("#imgName").val(),"containerId":msg.data.containerId});
                                    if($("#imgName").val() == ""){
                                        Alert1.content = "请输入镜像名称";
                                        Alert1.init();
                                        Alert1.show();
                                    }else{
                                        loading1.show();
                                        $.ajax({
                                            type: "post",
                                            url: "image/create",
                                            dataType:'json',
                                            contentType:'application/json',
                                            data: json,
                                            async: true,
                                            success: function (msg) {
                                                loading1.hide();
                                                if(msg.code == 200) {
                                                    Alert1.content = "保存镜像成功";
                                                    $("#imgName").val("");
                                                    $(".popup,.masking").hide();
                                                    var url = $("#ifBox").attr("src");
                                                    $("#ifBox").attr("src", url);
                                                    Alert1.init();
                                                    Alert1.show();
                                                }else{
                                                    Alert1.content = msg.message;
                                                    Alert1.init();
                                                    Alert1.show();
                                                    return false;
                                                }
                                            }
                                        });
                                    }

                                });
                            });
                        } else {
                            Alert1.content = msg.message;
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }
                    }
                });
            });
            $(".cancel").off("click").click(function () {
                var id = Number($(this).attr("data-id"));
                var json = {"imageId":id};
                loading1.show();
                $.ajax({
                    type: "get",
                    url: "image/unshare",
                    data:json,
                    async: true,
                    success: function (msg) {
                        loading1.hide();
                        if(msg.code == 200) {
                            Alert1.content = "取消到公有成功";
                            Alert1.success = function () {
                                self.tabelList(jsonS);
                            };
                            self.status = false;
                            Alert1.init();
                            Alert1.show();
                        } else {
                            Alert1.content = msg.message;
                            self.status = true;
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }
                    }
                });
            });
            $(".submit").off("click").click(function () {
                var id = Number($(this).attr("data-id"));
                var json = {"imageId":id};
                loading1.show();
                $.ajax({
                    type: "get",
                    url: "image/share",
                    data:json,
                    async: true,
                    success: function (msg) {
                        loading1.hide();
                        if(msg.code == 200) {
                            Alert1.content = "同步到公有成功";
                            Alert1.success = function () {
                                self.tabelList(jsonS);
                            };
                            self.status = false;
                            Alert1.init();
                            Alert1.show();
                        } else {
                            Alert1.content = msg.message;
                            self.status = true;
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }
                    }
                });
            });
            $(".detailBtn").off("click").click(function () {
                var id = Number($(this).attr("data-id"));
                var json = {"id":id};
                confirm1.content = "确定删除当前镜像吗？";
                json.isForced = false;
                confirm1.success = function () {
                    loading1.show();
                    $.ajax({
                        type: "get",
                        url: "image/delete",
                        data:json,
                        async: true,
                        success: function (msg) {
                            loading1.hide();
                            if(msg.code == 200) {
                                Alert1.content = "删除镜像成功";
                                Alert1.success = function () {
                                    self.tabelList(jsonS);
                                };
                                self.status = false;
                                Alert1.init();
                                Alert1.show();
                            }  else if(msg.code == 500401){
                                confirm1.content = msg.message;
                                confirm1.success = function () {
                                    loading1.show();
                                    json.isForced = true;
                                    $.ajax({
                                        type: 'get',
                                        url: "image/delete",
                                        async: true,
                                        data: json,
                                        success: function (msg) {
                                            loading1.hide();
                                            if (msg.code == 200) {
                                                Alert1.content = "删除成功";
                                                Alert1.success = function () {
                                                    window.location.reload(true);
                                                };
                                                Alert1.init();
                                                Alert1.show();
                                            }else{
                                                Alert1.content = msg.message;
                                                Alert1.init();
                                                Alert1.show();
                                            }
                                        }
                                    });
                                };
                                confirm1.init();
                                confirm1.show();
                            }else {
                                Alert1.content = msg.message;
                                self.status = true;
                                Alert1.init();
                                Alert1.show();
                                return false;
                            }
                        }
                    });
                };
                confirm1.init();
                confirm1.show();
            });
        },
        tabelList:function(jsons) {
            var self = this;
            loading1.show();
            // json = JSON.stringify(jsons);
            $.ajax({
                type: "get",
                url: "image/page",
                data: jsons,
                async: true,
                success: function(msg) {
                    loading1.hide();
                    // msg = JSON.parse(msg);
                    if(msg.code == 200) {
                        $tableBox.empty();
                        if(msg.data.list.length != 0) {
                            //列表
                            var tabel = "";
                            var startRow = msg.data.startRow;
                            $.map(msg.data.list, function(opt) {
                                tabel += tabelModel(opt,startRow);
                                startRow++;
                            });
                            $tableBox.append(th + tabel);
                            self.exchange(jsons);
                        } else {
                            var trImg = "<tr><td colspan='5'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td></tr>";
                            $tableBox.append(th + trImg)
                        }
                        var sumpage = msg.data.pages;
                        if(sumpage == 0){
                            sumpage = 1;
                        }
                        var nowpage = 1;
                        var pagenumber = 10;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {
                                nowpage = p;
                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                var jsonStr = jsons;
                                jsonStr.pageNum = nowpage;
                                loading1.show();
                                $.ajax({
                                    type: "get",
                                    url: "image/page",
                                    data: jsonStr,
                                    async: true,
                                    success: function(msg) {
                                        //列表
                                        loading1.hide();
                                        // msg = JSON.parse(msg);
                                        $tableBox.empty();
                                        var tabel = "";
                                        var startRow = msg.data.startRow;
                                        $.map(msg.data.list, function(opt) {
                                            tabel += tabelModel(opt,startRow);
                                            startRow++;
                                        });
                                        $tableBox.append(th + tabel);
                                        self.exchange(jsonStr);
                                    }
                                });
                            }
                        });
                    } else {
                        Alert1.content = msg.message;
                        Alert1.init();
                        Alert1.show();
                        return false;
                    }

                }
            });

        }
    };
    virMachineSch.init();
    // startWebSocket();
//		var star = new startWebSocket();
//		star.onmessage();
    //桌面共享
    function startWebSocket(containerId) {
        var path = "";
        $.ajax({
            type:"get",
            url: "common/project",
            async: true,
            success: function(msg) {
                if(msg.code == 200){
                    path = msg.data;
                    // var path = window.location.host+"/";
                    var wsuri = "ws://" + path + "webSocket/image/" + containerId ;
                    if('WebSocket' in window) {
                        ws = new WebSocket(wsuri);
                    } else if('MozWebSocket' in window) {
                        ws = new MozWebSocket(wsuri);
                    } else {
                        Alert1.content = "当前浏览器不支持websocket，不能进行桌面共享";
                        Alert1.init();
                        Alert1.show();
                    }
                    var myDate = new Date();
                    ws.onopen = function() {

                        console.log(myDate.getDate() + ":" + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + ":" + myDate.getMilliseconds() + "--onopen");
                    };
                    ws.onmessage = function(evt) {


                    };

                    ws.onclose = function(evt) {
                        console.log(myDate.getDate() + ":" + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + ":" + myDate.getMilliseconds() + "--onclose");
                    };
                    ws.onerror = function() {
                        console.log(myDate.getDate() + ":" + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + ":" + myDate.getMilliseconds() + "--onerror");
                    };
                }
            }
        });

    }

});